package com.itheima.web.servlet;


import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import com.itheima.util.EmailUtil;
import com.itheima.util.JsonUtils;
import com.itheima.util.VerificationCodeCache;
import com.itheima.util.VerificationCodeUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet{
    private UserService userService = new UserServiceImpl();

    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取用户名和密码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //如果前端axios采用post方式来发送的话，就使用这个方式来接收并且解析数据
//        BufferedReader br=request.getReader();
//        String params=br.readLine();
//        System.out.println(params);
//
//        HashMap<String,Object> hashMap= JsonUtils.jsonStringToHashMap(params);
//        System.out.println(hashMap);
//        //{remember=true, password=123, username=zhangsan}

//        String username =  hashMap.get("username").toString();
//        String password =hashMap.get("password").toString() ;
//        String remember = hashMap.get("remember").toString();
//        System.out.println(username);
//        System.out.println(password);
//        System.out.println(remember);
        //如果前端axios采用get方式来发送的话，就使用这个方式来接收并且解析数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //获取复选框数据
        String remember = request.getParameter("remember");

        System.out.println(username);
        System.out.println(password);
        System.out.println(remember);//String
//        System.out.println(remember.getClass());//String

        //2. 调用service查询
        User user = userService.login(username, password);

        //3. 判断
        if(user != null){
            //登录成功，跳转到查询所有的BrandServlet

            //判断用户是否勾选记住我
            if("true".equals(remember)){
                //勾选了，发送Cookie

                //1. 创建Cookie对象
                Cookie c_username = new Cookie("username",username);
                Cookie c_password = new Cookie("password",password);
                // 设置Cookie的存活时间
                c_username.setMaxAge( 60 * 60 * 24 * 7);
                c_password.setMaxAge( 60 * 60 * 24 * 7);
                //2. 发送
                response.addCookie(c_username);
                response.addCookie(c_password);
            }
            response.getWriter().write("loginSuccess");

        }else {
            // 登录失败,

           response.getWriter().write("loginerror");

        }
    }
//判断用户名是否在数据库中已经存在
    public void confirmUserByName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        //1. 获取用户名
        String username = request.getParameter("username");

        User user=userService.selectByUsername(username);
//        System.out.println(user);

        if(user!=null){
            response.getWriter().write("user_exists");
        }

    }
    public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //1. 获取用户名和密码数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username);

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        // 获取用户输入的验证码
        String checkCode = request.getParameter("checkCode");

        // 程序生成的验证码，从Session获取
        HttpSession session = request.getSession();
        String checkCodeGen = (String) session.getAttribute("checkCodeGen");

        // 比对
        if(!checkCodeGen.equalsIgnoreCase(checkCode)){ // 表示忽略字母大小写来比对
           response.getWriter().write("Verification_code_error");
            // 不允许注册
            return;
        }

        //2. 调用service 注册
        boolean flag = userService.register(user);
        //3. 判断注册成功与否
        if(flag){
            response.getWriter().write("register_success");
        }else {
            response.getWriter().write("register_error");
        }


    }
    public void getQQCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取用户名和密码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String qqNumber = request.getParameter("qqNumber");
        System.out.println(qqNumber);
        String toEmail = qqNumber+"@qq.com";
        System.out.println(toEmail);

        // 校验是否能发送验证码
        if (!VerificationCodeCache.canSendVerificationCode(toEmail)) {
//            System.out.println("验证码请求过于频繁，请稍后再试！");
            response.getWriter().write("toofrequent");
            return;
        }
        // 生成验证码
        String verificationCode = VerificationCodeUtil.generateCode();
        // 保存验证码
        VerificationCodeCache.saveVerificationCode(toEmail, verificationCode);
        // 发送验证码到邮箱
        if (EmailUtil.sendVerificationCode(toEmail, verificationCode)) {
            System.out.println("验证码已发送，请查收邮件！");
        }

        System.out.println(verificationCode);
        response.getWriter().write(verificationCode);


    }
    public void qq_login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取用户名和密码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String qqNumber = request.getParameter("qqNumber");
        String verificationCode = request.getParameter("verificationCode");
        String toEmail = qqNumber+"@qq.com";


        System.out.println(qqNumber);
        System.out.println(toEmail);
        System.out.println(verificationCode);

        // 校验验证码
        if (verificationCode.equals(VerificationCodeCache.getVerificationCode(toEmail))) {
//            System.out.println("验证码验证成功！");
            response.getWriter().write("success");
        } else {
            response.getWriter().write("error");
            //System.out.println("验证码错误！");
        }
    }

}
